package com.techcity;

import org.apache.hadoop.hive.ql.exec.UDAF;
import org.apache.hadoop.hive.ql.exec.UDAFEvaluator;

// create temporary function flooravg as 'com.techcity.FloorAvg';
public class FloorAvg extends UDAF {
    public static class FloorAvgState {
        private long mCount;
        private long sum_casual;
        private long sum_registered;
    }
    public static class FloorAvgEvaluator implements UDAFEvaluator {
        FloorAvgState state;
        public FloorAvgEvaluator(){
            super();
            state = new FloorAvgState();
            init();
        }
        /**
         * init函数类似于构造函数，用于UDAF的初始化
         */
        @Override
        public void init() {
            state.mCount=0;
            state.sum_casual=0;
            state.sum_registered=0;
        }

        /**
         * iterate接收传入的参数，并进行内部的轮转。其返回类型为boolean * * @param o * @return
         */

        public boolean iterate(long a,long b) {

            state.sum_casual += a;
            state.sum_registered += b;
            state.mCount++;
            return true;
        }

        /**
         * terminatePartial无参数，其为iterate函数遍历结束后，返回轮转数据， * terminatePartial类似于hadoop的Combiner * * @return
         */
        public FloorAvgState terminatePartial(){
            return state.mCount == 0 ? null : state;
        }

        /**
         * merge接收terminatePartial的返回结果，进行数据merge操作，其返回类型为boolean * * @param o * @return
         */
        public boolean merge(FloorAvgState floorAvgState){
            if(floorAvgState!=null){
                state.mCount += floorAvgState.mCount;
                state.sum_casual+=floorAvgState.sum_casual;
                state.sum_registered +=floorAvgState.sum_registered;
            }
            return true;
        }

        /**
         * terminate返回最终的聚集函数结果 * * @return
         */
        public String terminate() {
            return state.mCount == 0 ? null : state.sum_casual/state.mCount+" "
                    +state.sum_registered/state.mCount+" "
                    +(state.sum_casual/state.mCount+state.sum_registered/state.mCount);
        }
    }
}
